{% extends base %}

{% block head %}

<style type="text/css">

label {
    display: inline-block;
    width: 100px;
}

</style>

{% end %}

{% block body %}

<script type="text/javascript" src="/static/lib/vue/vue-2.2.6.min.js"></script>

<div class="col-md-12 card">
    {% set title = "图片合并" %}
    {% include "tools/base_title.html" %}

    <p>
        点击画布上的方块可以选择图片填充，选择多个图片依次水平往后填充,
        编辑完成之后点击预览按钮可以获取去除背景和方格的图片，设置列数和行数都为1可以用来调整图片大小,
        右键图片进行保存
    </p>
</div>

<div id="app" class="card">
    <input type="file" name="file" id="file" value="选择图片" onchange="handleFiles(this.files)" class="hide" multiple="multiple">
    <div class="col-md-12">
            <label>列数</label>
            <input type="text" id="cols" value="4">
        <br/>
            <label>行数</label>
            <input type="text" id="rows" value="4">
        <br/>
            <label>每帧宽度</label>
            <input type="text" id="width" value="64">
        <br/>
            <label>每帧高度</label>
            <input type="text" id="height" value="64">
        <p>
            <button id="createCanvasBtn">创建画布</button>
            <button id="toggleResult">预览</button>
        </p>
    </div>

    <div id="inputImageDiv" class="col-md-12">
    </div>

    <div id="canvasContainer" class="row top-offset-1">
        <canvas id="canvas"></canvas>
        <canvas id="realCanvas" class="hide"></canvas>
    </div>

    <img id="targetImage" class="hide">
</div>

<script type="text/javascript">

var globals = {};

// @deprecated 此方法已废弃
function repaint(images) {
    if (images.length == 0) {
        return;
    }
    var cols = parseInt($("#cols").val());
    var rows = parseInt($("#rows").val());
    var canvas = document.getElementById('canvas');
    var first = images[0];

    var width = first.width;
    var height = first.height;
    canvas.width  = cols * first.width;
    canvas.height = rows * first.height;
    var ctx = canvas.getContext('2d');
    for (var j = 0; j < rows; j++) {
        for (var i = 0; i < cols; i++) {
            var index = i * cols + j * rows;
            var img = images[index];
            var x = width * i;
            var y = height * j;
            ctx.drawImage(img, x, y, width, height);
        }
    }
}

function handleFiles(files) {
    var startX = globals.clickCol;
    var startY = globals.clickRow;
    if(files.length) {  
        var handled = 0;
        var fileLength = files.length;
        var images = [];
        
        for (var i = 0; i < files.length; i++) {
            var file = files[i];  
            var reader = new FileReader();  
            var img = $("<img>");

            // 创建URL对象
            var url = window.URL.createObjectURL(file)
            console.log(url);
            (function (url, index) {            
                var img = new Image();
                img.src = url;
                window.imgMap[startX + "-" + startY] = img;
                img.onload = function(event)  {  
                    // document.getElementById("filecontent").innerHTML = this.result;  
                    var img = event.target;
                    // console.log(event);
                    ctx.drawImage(img, 0, 0, img.width, img.height, 
                        startX + index * getFrameWidth(), startY, getFrameWidth(), getFrameHeight());
                    realCtx.drawImage(img, 0, 0, img.width, img.height, 
                        startX + index * getFrameWidth(), startY, getFrameWidth(), getFrameHeight());
                };  
            })(url, i);
            // reader.readAsDataURL();
        }

        // 生成下载链接
        // Chrome报错 Not allowed to navigate top frame to data URL
        // var canvas = $("#canvas")[0];
        // console.log(canvas.toDataURL("image/png"));
        // $("#downloadLink").attr("href", canvas.toDataURL("image/png"));
    }
  }  

function getFrameWidth () {
    return parseInt($("#width").val());
}

function getFrameHeight () {
    return parseInt($("#height").val());
}

function alignFloor(value, alignment) {
    return parseInt(value / alignment) * alignment;
}

$("#createCanvasBtn").on("click", function() {
    var cols = parseInt($("#cols").val());
    var rows = parseInt($("#rows").val());
    var width = parseInt($("#width").val());
    var height = parseInt($("#height").val());

    var canvas = $('#canvas')[0];
    canvas.width = width * cols;
    canvas.height = height * rows;

    var realCanvas = $("#realCanvas")[0];
    realCanvas.width = canvas.width;
    realCanvas.height = canvas.height;

    var ctx = canvas.getContext('2d');
    ctx.fillStyle = "#ccf";
    ctx.fillRect(0,0,canvas.width, canvas.height);

    for (var i = 1; i < cols; i++) {
        ctx.fillStyle = "#cf8";
        ctx.moveTo(width*i, 0);
        ctx.lineTo(width*i, canvas.height);
        ctx.stroke();
    }

    for (var i = 1; i < rows; i++) {
        ctx.fillStyle = "#cf8";
        ctx.moveTo(0, height * i);
        ctx.lineTo(canvas.width, height*i);
        ctx.stroke();
    }

    window.ctx = ctx;
    window.realCtx = realCanvas.getContext("2d");
    window.canvasClickEvents = [];
    window.imgMap = {};
})

$("#canvas").on("click", function (event) {
    console.log(event);
    var x = event.offsetX;
    var y = event.offsetY;
    var canvas = $('#canvas')[0];

    x = alignFloor(x, getFrameWidth());
    y = alignFloor(y, getFrameHeight());

    globals.clickCol = x;
    globals.clickRow = y;
    $("#file").click();
})

$("#toggleResult").on("click", function (event) {
    var canvas = $("#realCanvas")[0];
    if ($("#targetImage").hasClass('hide')) {
        // 编辑 -> 预览
        // $("#realCanvas").removeClass("hide");
        $("#targetImage").removeClass('hide');
        $("#canvas").addClass('hide');
        $("#toggleResult").text("编辑");
        // 生成图片
        $("#targetImage").attr("src", canvas.toDataURL());
    } else {
        // 预览 -> 编辑
        // $("#realCanvas").addClass('hide');
        $("#targetImage").addClass('hide');
        $("#canvas").removeClass("hide");
        $("#toggleResult").text("预览");
    }
});

$("#downloadFile").click(function (event) {
    var canvas = $('#canvas')[0];
    downloadFile("image.png", canvas.toDataURL("image/png"));
})

$(function() {
    window.canvasClickEvents = [];
    $("#createCanvasBtn").click();
});

function base64Img2Blob(code){
    var parts = code.split(';base64,');
    var contentType = parts[0].split(':')[1];
    var raw = window.atob(parts[1]);
    var rawLength = raw.length;

    var uInt8Array = new Uint8Array(rawLength);

    for (var i = 0; i < rawLength; ++i) {
      uInt8Array[i] = raw.charCodeAt(i);
    }

    return new Blob([uInt8Array], {type: contentType}); 
}
function downloadFile(fileName, url){
    try {
        console.log(fileName, url)
        // url = url.replace("image/png", "application/octet-stream");
        // window.location.href = url;
        window.open(url, fileName);
        // var aLink = document.createElement('a');
        // var aLink = $("#downloadLink")[0];
        // var evt = document.createEvent("HTMLEvents");
        // evt.initEvent("click", false, false);//initEvent 不加后两个参数在FF下会报错
        // aLink.download = fileName;
        // aLink.href = url;
        // aLink.dispatchEvent(evt);
        // $("#downloadLink").click();
    } catch (e) {
        alert(e);
    }
}           
</script>

{% end %}